package com.netty.go.start;

import com.netty.go.config.NettyConfigProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;

@Component
public class NettyStart {

    private static final Logger log = LoggerFactory.getLogger(NettyStart.class);

    @Resource
    NioEventLoopGroup mainGroup;
    @Resource
    NioEventLoopGroup subGroup;
    final ServerBootstrap serverBootstrap;
    final NettyConfigProperties nettyProperties;

    public NettyStart(ServerBootstrap serverBootstrap, NettyConfigProperties nettyProperties) {
        this.serverBootstrap = serverBootstrap;
        this.nettyProperties = nettyProperties;
    }

    /**
     * 启动netty
     *
     * @throws InterruptedException
     */
    @PostConstruct
    public void start() throws InterruptedException {
        // 绑定端口启动
        serverBootstrap.bind(nettyProperties.getPort()).sync();
        // 备用端口
        serverBootstrap.bind(nettyProperties.getPortSalve()).sync();
        log.info("启动Netty: {},{}", nettyProperties.getPort(), nettyProperties.getPortSalve());
    }

    /**
     * 关闭netty
     */
    @PreDestroy
    public void close() {
        log.info("关闭Netty");
        mainGroup.shutdownGracefully();
        subGroup.shutdownGracefully();
    }

}
